// pages/shop-car/shop-car.js
var api = require('../../config/api.js');
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {

    'checkAll': true,
    itemCheckAll: true,
    'totalCount': 0,
    'totalPrice': 0,
    startX: 0, //开始坐标
    startY: 0,
    page: 1,
    glshow: false
  },
  //猜你喜欢
  getHotData() {
    let that = this;
    util.request(api.HotGoods).then(function (res) {
      if (res.errno == 0) {
        that.setData({
          hotList: res.data
        })

      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //获取购物车列表
  getData() {
    let that = this;
    util.request(api.CarIndex).then(function (res) {
      if (res.errno == 0) {
        that.setData({
          // goodList: res.data.cartList
          storeList: res.data.litemallBrands
        })
        that.isAllCheck();
        that.calculateTotal();
      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //修改勾选状态
  getCheckData(upcheck, pid) {
    let that = this;
    util.request(api.CartChecked, {
      productIds: pid,
      isChecked: upcheck
    }, 'post').then(function (res) {
      if (res.errno == 0) {
        that.setData({
          storeList: res.data.litemallBrands,
          checkAll: true
        })
        for (var x in res.data.litemallBrands) {
          if (res.data.litemallBrands[x].checked == false) {
            that.setData({
              checkAll: false
            })
          }
        }
        that.isAllCheck();
        that.calculateTotal();
      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //点击商铺全选
  selectItemalltap(e) {
    var value = e.detail.value;

    if (value && value[0]) {
      checkAll = true;
    }

    var goodList = this.data.storeList;

    for (var i = 0; i < goodList.length; i++) {
      var good = goodList[i];
      good['checked'] = checkAll;
    }

    this.setData({
      'checkAll': checkAll,
      'goodList': goodList
    });
    this.calculateTotal();
  },
  /**
   * 首次判断是否全选
   */
  isAllCheck() {
    var list = this.data.storeList;
    for (var x in list) {

      if (list[x].checked == false) {
        this.setData({
          checkAll: false
        })
        break;
      }
    }
  },


  /**
   * 用户选择购物车商品
   */
  checkboxChange: function (e) {
    var checkboxItems = this.data.storeList;
    var values = e.detail.value;
    console.log("values--", values)
    for (var i = 0; i < checkboxItems.length; ++i) {
      checkboxItems[i].checked = false;
      for (var y = 0; y < checkboxItems[i].cartList.length; ++y) {

        for (var j = 0; j < values.length; ++j) {
          if (checkboxItems[i].id == values[j]) {
            checkboxItems[i].checked = true;
            break;
          }
        }
      }

    }

    var checkAll = false;
    console.log("checkboxItems.length--", checkboxItems.length)
    if (checkboxItems.length == values.length) {
      checkAll = true;
    }

    this.setData({
      'storeList': checkboxItems,
      'checkAll': checkAll
    });
    this.calculateTotal();

  },
  /**
   * 计算商品总数
   */
  calculateTotal: function () {
    var goods = [];
    var storeList = this.data.storeList;
    var totalCount = 0;
    var totalPrice = 0;
    for (var x in storeList) {
      for (var i in storeList[x].cartList) {
        if (storeList[x].cartList[i].checked) {
          totalCount += storeList[x].cartList[i].number;
          totalPrice += storeList[x].cartList[i].number * storeList[x].cartList[i].price;
          goods.push(storeList[x].cartList[i]);
        }
      }
    }

    totalPrice = totalPrice.toFixed(2);
    this.setData({
      'totalCount': totalCount,
      'totalPrice': totalPrice,
      "goods": goods
    })
  },
  /**
   * 用户点击商品减1
   */
  subtracttap: function (e) {
    var number = e.target.dataset.number;
    var id = e.target.dataset.id;
    var productId = e.target.dataset.productid;
    var goodsId = e.target.dataset.goodsid;
    var that = this;


    if (number <= 1) {
      return;
    } else {
      util.request(api.CartUpdate, {
        id: id,
        productId: productId,
        number: number - 1,
        goodsId: goodsId
      }, 'post').then(function (res) {
        if (res.errno == 0) {
          that.setData({
            storeList: res.data.data.litemallBrands
          });
          that.calculateTotal();

        } else {
          util.myToast(res.errmsg)
        }
      });


    }
  },

  /**
   * 用户点击商品加1
   */
  addtap: function (e) {
    var number = e.target.dataset.number;
    var id = e.target.dataset.id;
    var productId = e.target.dataset.productid;
    var goodsId = e.target.dataset.goodsid;
    var that = this;

    util.request(api.CartUpdate, {
      id: id,
      productId: productId,
      number: number + 1,
      goodsId: goodsId
    }, 'post').then(function (res) {
      if (res.errno == 0) {

        that.setData({
          storeList: res.data.data.litemallBrands
        });
        that.calculateTotal();

      } else {
        util.myToast(res.errmsg)
      }
    });

  },
  /**
   * 用户点击全选
   */
  selectalltap: function (e) {
    console.log(e);
    var value = e.detail.value;
    var checkAll = false;
    if (value && value[0]) {
      checkAll = true;
    }

    var goodList = this.data.storeList;
    for (var i = 0; i < goodList.length; i++) {
      var good = goodList[i];
      good['checked'] = checkAll;
    }

    this.setData({
      'checkAll': checkAll,
      'storeList': goodList
    });
    this.calculateTotal();
  },
  /**
   * 左滑删除商品
   */
  delgoods(e) {
    var id = e.target.dataset.id;
    var index = e.target.dataset.index;
    var productId = e.target.dataset.productid;
    var list = this.data.storeList;
    var that = this;
    util.request(api.CartDelete, {
      id: id,
      productId: productId,

    }, 'post').then(function (res) {
      if (res.errno == 0) {
        // list[index].checked == false;
        // list.splice(index, 1);

        that.setData({
          storeList: res.data.litemallBrands
        })
        that.calculateTotal();
        that.isAllCheck();
      } else {
        util.myToast(res.errmsg)
      }
    });





  },
  //点击改变状态
  onItemClick(e) {
    var upcheck = e.currentTarget.dataset.check;
    var pid = e.currentTarget.dataset.pid;
    //更改选择状态
    this.getCheckData(!upcheck, pid);
  },

  onItemAllSelect(e) {
    var index = e.currentTarget.dataset.index;

  },
  //点击改变全部状态，全部选中
  onAllSelect(e) {

    var list = this.data.storeList;
    var arr_pid = '';
    var arr_check = true;
    for (var x in list) {
      for (var j in list[x].cartList) {
        arr_pid = arr_pid + list[x].cartList[j].productId + ','
      }

    }
    //去掉最后一位逗号
    arr_pid = arr_pid.substr(0, arr_pid.length - 1);
    this.getCheckData(arr_check, arr_pid);
  },
  //点击改变全部状态，全部不选中
  onAllNoSelect(e) {
    var list = this.data.storeList;
    var arr_pid = '';
    var arr_check = false;
    for (var x in list) {
      for (var j in list[x].cartList) {
        arr_pid = arr_pid + list[x].cartList[j].productId + ','
      }

    }
    //去掉最后一位逗号
    arr_pid = arr_pid.substr(0, arr_pid.length - 1);
    this.getCheckData(arr_check, arr_pid);
  },
  //去结算
  onBuy() {
    if (this.data.totalCount == 0) {
      util.myToast("请选择货品")
    } else {
      wx.navigateTo({
        url: '/pages/submit-order/submit-order'
      })
    }


  },
  //猜你喜欢详情
  onLikeItemClick(e) {
    var id = e.currentTarget.dataset.id;
    util.toClass('/pages/details/details', {
      goodsid: id
    })
  },
  //购物车进入详情
  onItemDetails(e){
    var id = e.currentTarget.dataset.goodsid;
    util.toClass('/pages/details/details', {
      goodsid: id
    })
  },
  //快速加入购物车
  onAddShop(e) {
    var id = e.currentTarget.dataset.id;
    this.getAddCar(id);
  },
  //加入购物车
  getAddCar(goodsId) {
    let that = this;
    util.request(api.CartAdd, {
      number: 1,
      goodsId: goodsId
    }, 'post').then(function (res) {
      if (res.errno == 0) {
        wx.showToast({
          title: '加入购物车！',
        })
        that.getData();
      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //选择规格
  onItemChooseRule(e) {
    // var goodsid = e.currentTarget.dataset.goodsid;
    // this.setData({
    //   glshow: true,
    // })
    // this.getDetailsData(goodsid);
  },
  //关闭规格弹窗
  glClose(e) {
    this.setData({
      glshow: false
    })
  },

  // 商品详情获取
  getDetailsData: function (goodsid) {
    var that = this;
    util.request(api.detail, {
      id: goodsid,
    }, 'get').then(function (res) {
      if (res.errno === 0) {
        goodsInfo: res.data.productList[0]
      }
      else {
        util.myToast(res.errmsg)
      }

    });
  },
  //赠送礼品
  onSend(e) {
    var goods = this.data.goods;
    console.log("goods---", goods);
    var products = [];

    for (var i = 0; i < goods.length; i++) {
      var obj = {
        productId: '',
        num: ''
      }
      obj.productId = goods[i].productId;
      obj.num = goods[i].number;
      products.push(obj);
    }
    if (this.data.totalCount == 0) {
      util.myToast("请选择货品")
    } else {
      util.toClass('/pages/submit-order-send/submit-order-send', {
        products: JSON.stringify(products)
      })
    }

    console.log("products---", products);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getHotData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

})